import React,{useReducer} from 'react';

// state 是旧状态
function countReducer(state,action) {
    switch(action.type) {
        case 'add':
            return state + 1;  // 返回值是新状态
        case 'sub':
            return state - 1;
        default:
            return state;
    }
}

function Example() {

    const [count,dispatch] = useReducer(countReducer,0);
    return (
        <div>
            <h1>{count}</h1>
            {/* JSX 语法中的事件监听要传入一个函数 */}
            <button onClick={() => dispatch({type:'add'})}>+1</button>
            <button onClick={() => dispatch({type:'sub'})}>-1</button>
        </div>
    )
}

export default Example;